#include "../include/LandR.h"
#include "../include/serviceAnalysis.h"
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <time.h>

int Login(int identity, char *id, char *password){
	
	FILE *fp = NULL;				
	char path[30] = {"../"};			
	char rpsd[20];	

	if (identity == 0){
		strcat(path, "manager/");
	} else if (identity == 1){
		strcat(path, "service/");
	} else if (identity == 2 ){
		strcat(path, "customer/");
	}

	strcat(path,id);
	strcat(path,"/password.txt");				//get password file

	fp = fopen(path, "r");
	if (fp == NULL){
		printf("open password file error\n");		//file non-existent
		return -1;					//return -1
	}

	fgets(rpsd, 20, fp);
	fclose(fp);	

	if(strncmp(password, rpsd, strlen(password)) == 0){	//right password
		return 0;
	}

	printf("password error\n");				
	return -1;
}



int mkfile(char *path,char *filename){				//mk file
	char filepath[30];
	int ret;	

	strcpy(filepath, path);
	strcat(filepath, filename);
	ret = creat(filepath, 0755);
	if (ret < 0){
		printf("mkfile error\n");
		return -1;
	}
	return 0;
}

char* Register(int identity, char *name, char *password){

	FILE *fp = NULL;
	char *res = (char *) malloc(sizeof(char)*20);				
	char path[30] = {"../"};		
	char idpath[30] = {0};	
	char passwordpath[30] = {0};
	char buf[30] = {0};
	int id;
	int ret;
	
	if (identity == 0){
		strcat(path, "manager/");
		id = 101;
	} else if (identity == 1){
		strcat(path, "service/");
		id = 201;
	} else if (identity == 2 ){
		strcat(path, "customer/");
		id = 301;
	}

	strcpy(idpath,path);
	strcat(idpath,"id.txt");			//get id file
	fp = fopen(idpath, "r+");
	if (fp == NULL){
		printf("open id file error\n");		//file non-existent
		return NULL;				//return NULL
	}

	while (fgets(buf, 100, fp) != NULL){
		id++;
	}

	sprintf(res, "%3d", id);				//write id and name to id.txt
	fputs(res, fp);
	fputs(" ", fp);
	fputs(name, fp);
	fputs("\n",fp);	

	fclose(fp);
	
	strcat(path,res);	
	ret = mkdir(path, 0775);			//mkdir
	if (ret < 0){					//mkdir error
		printf("mkdir error\n");
		return NULL;
	}
	strcat(path, "/");
	
	mkfile(path, "password.txt");			//mk some user txt
	mkfile(path, "information.txt");
	mkfile(path, "offLineMessage.txt");

	strcpy(passwordpath, path);
	strcat(passwordpath, "password.txt");			
	fp = fopen(passwordpath, "w");

	fputs(password, fp);				//write password

	fclose(fp);	

	strcat(path,"information.txt");
	fp = fopen(path, "w");

	fputs(name, fp);				//write path

	fclose(fp);	

	return res;
}


int isOnline(char *identity, char *acount){		//judge  user is online?

	int res;
	FILE *fp;
	char path[80];
	char buf[200];

	if (strcmp(identity, "service") == 0){				//sure the identity
		strcpy(path, "../service/online/onlineList.txt");
 	} else {
		strcpy(path, "../customer/online/onlineList.txt");
	}

	printf("%s\n", path);
	fp = fopen(path, "r+");

	if(fp != NULL)
		printf("fp is not NULL\n");
	while (fgets(buf, 200, fp) != NULL){
		
		int n = 0;
		int i;
		for(i=0;i<3;i++){
			if (buf[i] == acount[i]){			//find in the online list
				n++;
			}
		}
		if (n == 3){
			fclose(fp);
		
			if (strcmp(identity, "service") == 0){
				strcpy(path, "../service/online/");
 			} else {
				strcpy(path, "../customer/online/");
			}
			strcat(path, acount);
			
			fopen(path, "r+");
			fgets(buf, 200, fp);
			
			fclose(fp);
			res = buf[0]-'0';
			return res;		
		}
	}

	fclose(fp);
	return -1;
}

int sendMsg(char *identity, char *send, char *rsv, char *msg){
	
	int res;
	FILE *fp;
	time_t timep;
	char path[30];
	char acountpath[30];
	char buf[200];

	printf("%s %s %s %s\n",identity,send,rsv,msg);
	if (strcmp(identity, "service") == 0){				//identity is service

		printf("service send\n");
		if (rsv[0] != '3'){
			printf("rsv error\n");
			res = -2;
			return 	res;
		}
		strcpy(path, "../service/");
		strcat(path, send);
		strcat(path, "/");
		strcat(path, send);
		strcat(path, rsv);
		
		fp = fopen(path, "r+");

		if (fp == NULL) {
			mkfile(path, "");
			fp = fopen(path, "r+");
		}
	
		while (fgets(buf, 200, fp) != NULL);

		time(&timep);
		strcpy(buf, asctime(gmtime(&timep)));			//get the time

		fputs(buf, fp);
		strcpy(buf, send);
		strcat(buf, " ");
		strcat(buf, rsv);
		strcat(buf," ");
		strcat(buf, msg);
		strcat(buf, "\n");
		fputs(buf, fp);						//save in the chat memory
		
		fclose(fp);
		
		int n;
		if ((n = isOnline("custom", rsv)) == -1){		//if user is offonline

			res = -1;
			strcpy(path, "../customer/");
			strcat(path, rsv);
			strcat(path, "/offLineMessage.txt");		
			fp = fopen(path, "r+");

			while (fgets(buf, 200, fp) != NULL);
			time(&timep);
			strcpy(buf, asctime(gmtime(&timep)));

			fputs(buf, fp);
			strcpy(buf, send);
			strcat(buf, " ");
			strcat(buf, rsv);
			strcat(buf," ");
			strcat(buf, msg);
			strcat(buf, "\n");
			printf("%s\n", buf);
			fputs(buf, fp);

			fclose(fp);
			return res;
		} else {						//if is online
						

			time(&timep);
			strcpy(buf, asctime(gmtime(&timep)));
			strcat(buf, send);
			strcat(buf, " ");
			strcat(buf, rsv);
			strcat(buf," ");
			strcat(buf, msg);
			strcat(buf, "\n");

			strcpy(path, "../customer/");
			strcat(path, rsv);
			strcat(path, "/msg");
			fp = fopen(path, "w+");
			fputs(buf, fp);
			fclose(fp);

			strcpy(path, "../customer/");
			strcat(path, rsv);
			strcat(path, "/flag");
			fp = fopen(path, "w+");
			fclose(fp);
		}
		
		res = 1;
		return res;
	} else if ( strcmp(identity, "custom") == 0){		//identity is custom
		printf("custom\n");
		if (rsv[0] != '2'){
			res = -3;
			return 	res;
		}

		strcpy(path, "../service/");
		strcat(path, rsv);
		strcat(path, "/");
		strcat(path, rsv);
		strcat(path, send);
		
		printf("%s\n",path);
		fp = fopen(path, "r+");

		if (fp == NULL) {
			mkfile(path, "");
			fp = fopen(path, "r+");
		}
	
		while (fgets(buf, 200, fp) != NULL);

		time(&timep);
		strcpy(buf, asctime(gmtime(&timep)));

		fputs(buf, fp);
		strcpy(buf, send);
		strcat(buf, " ");
		strcat(buf, rsv);
		strcat(buf," ");
		strcat(buf, msg);
		strcat(buf, "\n");
		fputs(buf, fp);
		
		fclose(fp);
		
		int n;
		if ((n = isOnline("service", rsv)) == -1){

			res = -1;
			strcpy(path, "../service/");
			strcat(path, rsv);
			strcat(path, "/offLineMessage.txt");		
			fp = fopen(path, "r+");

			while (fgets(buf, 200, fp) != NULL);
			time(&timep);
			strcpy(buf, asctime(gmtime(&timep)));

			fputs(buf, fp);
			strcpy(buf, send);
			strcat(buf, " ");
			strcat(buf, rsv);
			strcat(buf," ");
			strcat(buf, msg);
			strcat(buf, "\n");
			printf("%s\n", buf);
			fputs(buf, fp);

			fclose(fp);
			return res;
		} else {
					

			time(&timep);
			strcpy(buf, asctime(gmtime(&timep)));
			strcat(buf, send);
			strcat(buf, " ");
			strcat(buf, rsv);
			strcat(buf," ");
			strcat(buf, msg);
			strcat(buf, "\n");

			strcpy(path, "../service/");
			strcat(path, rsv);
			strcat(path, "/msg");
			fp = fopen(path, "w+");
			fputs(buf, fp);
			fclose(fp);

			strcpy(path, "../service/");
			strcat(path, rsv);
			strcat(path, "/flag");
			fp = fopen(path, "w+");
			fclose(fp);
		}
		
		res = 1;
		return res;
	} 
	
	return res;
}


void offmsg(int identity, char *acount, int connfd){

	char path[40];
	char send[1024];
	char buf[400];
	FILE *fp;

	if (identity == 1){				//sure the identity
		strcpy(path, "../service/");
 	} else if (identity == 2){
		strcpy(path, "../customer/");
	} else {
		return ;
	}
	
	strcat(path, acount);
	strcat(path, "/offLineMessage.txt");		

	strcpy(send, "offmsg ");		
	fp = fopen(path, "r");
	
	if (fp == NULL){
		return ;
	}
	int flag = 0;

	while(fgets(buf, 400, fp) != NULL){	
		flag = 1;			//have off msg
		strcat(send, buf);
	}

	fclose(fp);
	fopen(path, "w");
	fclose(fp);

	if (flag == 0){
		strcat(send, "you have not a off-Line msg");
	}

	sleep(1);
	Write(connfd, send, strlen(send));				//send to client
}


#define N 1024
void back(char *who, char *a, char *b) {  // stdio.h  string.h stdilb.h    #define N = 100    //who Éí·Ý a³·»Ø·œid  ÍšÑ¶·œid 
   
    FILE *fp;
    FILE *fp1;
    char temp[10];
    char str[N + 1];     //ŽæŽ¢ŽÓÎÄŒþµ±ÖÐ¶Á³öÀŽµÄ×Ö·ûŽ® 
    char **c;      //ŽæŽ¢ ·Öžî×Ö·ûŽ®ºóµÄ×Ö·ûŽ®Êý×é 
    if ((*a-'0')>(*b-'0')) {
      strcpy(temp,b);
      strcpy(b,a);
      strcpy(a,temp);
      
    }
    char buff [100];
    strcpy(buff,"../service/");    // ¿Í·þµÄÄ¿ÂŒÏÂ 
  
  
    char buff1[10];        //Íš¹ýidµÃµœÎÄŒþÂ·Ÿ¶ 
    char buff2[10];
    char d[10];
     int num = 0;
    strcpy(buff1,a);
    strcpy(buff2,b);
    strcat(buff,a);
    strcat(buff,"/");
  strcat(buff1,buff2);
    strcat(buff,buff1);
    
    if ( (fp = fopen(buff, "rt")) == NULL || (fp1 = fopen("100", "w+")) == NULL  ) {   //ÅÐ¶ÏÎÄŒþÊÇ·ñŽò¿ªÊ§°Ü
        puts("Fail to open file!");
        exit(0);
    }

    while( fgets(str, N, fp) != NULL ) {    //¿Ž·¢ËÍ¶Ë·¢ËÍÁË¶àÉÙÌõÏûÏ¢ 
      c = strcut(str);
      if ((strcmp(c[0],who) ) == 0) {
     num  = num + 1;
      }
        
     }  

    fclose(fp);
    num  = num - 1;  
  int i= 0; 
  int j;            //ÔÙŽÎŽò¿ªÄ¿±êÎÄŒþ   ²»ÓÃ³·»ØµÄÏûÏ¢ÌõÊý 
    fp = fopen(buff, "rt");
    while( fgets(str, N, fp) != NULL ) {
      c = strcut(str);
    i = i + 1;       //·Öžî×Ö·ûŽ® 
      if ((strcmp(c[0],who) ) == 0 && num == 0) {  //Íš¹ýidÈ¥ÅÐ¶ÏÊÇ²»ÊÇ·¢ËÍ·œ·¢ËÍµÄÏûÏ¢  Èç¹ûÊÇ³·»ØµÄÏûÏ¢Õâ²»ÐŽÈëÎÄŒþ 
      j = i;
      continue;
      }
      if ((strcmp(c[0],who) ) == 0 && num != 0) {   // ²»ÐèÒª³·»ØµÄÏûÏ¢ÊýŒõÉÙ 
      num--;
      }
    
        fputs(str,fp1);     //œ«ÄÚÈÝÐŽÈëµœ ÎÄŒþÖÐ 
  
    }  
    fclose(fp);
    fclose(fp1);
   remove(buff);     //ÉŸ³ýÔ­±ŸµÄÎÄŒþ 
   
  if ((fp = fopen(buff, "w+" ))== NULL || (fp1 = fopen("100", "rt")) == NULL) {
     puts("Fail to open file!");
        exit(0);
    }
    
  
  i = 0 ;
   while( fgets(str, N, fp1) != NULL ) {   //œ«ÁÙÊ±ÎÄŒþµÄÀàÈÝÐŽ»ØÎÄŒþ 
      c = strcut(str);
      i = i + 1;
      if (i != j-1){
        fputs(str,fp);
      }
        
    
     }
    fclose(fp);
    fclose(fp1);
  remove("100");   //ÉŸ³ýÁÙÊ±ÎÄŒþ 
  
 }  
 

char *css(int connfd, char *service){

	char *res = (char *) malloc(sizeof(char)*10);
	int n = 999;
	char mini[10] = {"001"};
	char buf[20];
	char buf1[10];
	char send[1024];
	char path[40] = {"../service/online/"};
	char opath[30];
	char filepath[40] = {"../service/online/onlineList.txt"};
	FILE *fp,*p;

	fp = fopen(filepath, "r");

	while (fgets(buf, 200, fp) != NULL){
		buf[3] = '\0';
		if (strcmp(buf, service) == 0){
			continue;
		}
		strcpy(opath, path);
		strcat(opath, buf);
		p = fopen(opath, "r");
		fgets(buf1, 10, p);
		if (n > (buf1[0] - '0')){
			n = buf1[0] - '0';
			strcpy(mini, buf);
		}
		fclose(p);
	}
	
	fclose(fp);
	strcpy(opath, path);
	strcat(opath, mini);
	

	if (strcmp(mini, "001") == 0){
		strcpy(res, mini);
		Write(connfd, "have no service online", 23);
	} else {
		p = fopen(opath, "w");
		n++;
		sprintf(send, "%d", n);
		fputs(send, p);
		fclose(p);

		strcpy(res, mini);

		strcpy(send, mini);
		strcat(send, " service for you:");
		Write(connfd, send, strlen(send));
	}
	
	return res;
}
